#coding=utf-8
from uliweb import expose
import generic.views as g_views

get_url = g_views.get_url('/assignments', restful=True)
layout = 'assignments_layout.html'
model = 'assignment'

def __begin__():
    from uliweb import function
    return function('require_login')()

def boolean_convert(b, obj):
    if b:
        return '<div class="ui-icon ui-icon-check"></div>'
    else:
        return '<div class="ui-icon ui-icon-closethick"></div>'

@expose('/assignments/list')
@expose('/assignments')
def assignments_list():
    from uliweb.utils.generic import ListView
    from uliweb import orm
    from uliweb.core.html import Tag
    from uliweb.utils.common import get_choice
    from query import create_assignment_query
    
    Assignment = orm.get_model('assignment')
    
    query_view = create_assignment_query(url_for(assignments_list))
    c = query_view.run()
    
    condition = None
    query = None
    #增加显示未完成信息处理
    if request.GET.get('notcomplete') == '1':
        condition = (Assignment.c.stage != 'FN') & condition
    if c.get('tx'):
        condition = (Assignment.tx.in_(int(c['tx']))) & condition
    if c.get('name'):
        condition = (Assignment.c.ass_id.like('%'+c['name']+'%') | Assignment.c.name.like('%'+c['name']+'%')) & condition
    if c.get('kfzx'):
        condition = (Assignment.c.kfzx == int(c['kfzx'])) & condition
    if c.get('status'):
        condition = Assignment.c.status.in_(c['status']) & condition
    if c.get('requirement'):
        condition = (Assignment.requirements.in_(int(c['requirement']))) & condition
    if c.get('system'):
        condition = (Assignment.systems.in_(int(c['system']))) & condition
    if c.get('type'):
        condition = Assignment.c.type.in_(c['type']) & condition
    if c.get('stage'):
        condition = Assignment.c.stage.in_(c['stage']) & condition
    
    if request.user.department == '2':
        if request.user.is_gm:
            condition = (Assignment.c.kfzx == request.user._kfzx_) & condition
        else:
            ids = request.user.users_systems.ids()
            condition = Assignment.systems.in_(*ids) & condition
        
    if request.user.department == '1' and not request.user.is_gm:
        condition = Assignment.tx.in_(request.user._tx_) & condition
    
    def ass_id(value, obj):
        return str(Tag('a', value, href=url_for(assignments_view, id=obj.id)))
    
    def stage(value, obj):
        return get_choice(settings.PARA.ASSIGNMENT_STAGE[obj.type], value)
    
    pageno = int(request.values.get('page', 1)) - 1
    rows_per_page = int(request.values.get('rows', settings.get_var('PARA/ROWS_PER_PAGE', 10)))
    
    fields_convert_map = {'ass_id':ass_id, 'stage':stage, 'risk_if':boolean_convert, 'advanced_if':boolean_convert}
    
    _id = '%s_table' % model
    view =  ListView(model, condition=condition, rows_per_page=rows_per_page, 
        pageno=pageno, id=_id, fields_convert_map=fields_convert_map)
    
    if 'download' in request.values:
        def stage(value, obj):
            return unicode(get_choice(settings.PARA.ASSIGNMENT_STAGE[obj.type], value), 'utf8')
        fields_convert_map = {'stage':stage}
        return view.download('assignments.xls', action='download', timeout=0,
            fields_convert_map=fields_convert_map)
    else:
        data = {'query_form':query_view.form}
        return g_views.generic_list(model, get_url=get_url, layout=layout, template='assignments_list.html', add_button_text='增加任务书',
            view=view, data=data, json_result=True)

@expose('/assignments/add')
def assignments_add():
    from uliweb.utils.generic import AddView
    from uliweb.orm import get_model
    from forms import AssForm
    from functools import partial
    
    System = get_model('system')
    
    def post_created_form(fcls, model):
        fcls.systems.query = System.get_systems()
    
    view = AddView(model, partial(get_url, 'view'), form_cls=AssForm,
        post_created_form=post_created_form)
    
    return g_views.generic_add(model, get_url, layout=layout, title='增加任务书', view=view)

@expose('/assignments/<int:id>/edit')
def assignments_edit(id):
    from uliweb.utils.generic import EditView
    from uliweb.orm import get_model
    from forms import AssEditForm
    from functools import partial
    
    Assignment = get_model(model)
    System = get_model('system')
    obj = Assignment.get(int(id))
    
    def post_created_form(fcls, model, obj):
        fcls.stage.choices = settings.PARA.ASSIGNMENT_STAGE[obj.type]
        fcls.assignment = obj
        fcls.systems.query = System.get_systems()
        
    view = EditView(model, ok_url=partial(get_url, 'view'), 
        obj=obj, form_cls=AssEditForm, post_created_form=post_created_form)

    return g_views.generic_edit(model, id=id, get_url=get_url, layout=layout, 
        title='修改任务书', view=view)

@expose('/assignments/<int:id>/delete')
def assignments_delete(id):
    from uliweb.utils.generic import DeleteView
    from uliweb import orm
    
    Assignment = orm.get_model('assignment')
    Tasks = orm.get_model('tasks')
    Tasks_Develop = orm.get_model('tasks_develop')
    Researches = orm.get_model('researches')
    obj = Assignment.get(Assignment.c.id == int(id))
    
    if request.user.is_superuser or (request.user.department == '2' and request.user.is_gm and obj._kfzx_ == request.user._kfzx_):
        if obj.ass_tasks.count() > 0:
            flash('当前任务书下还存在与之关联的非开发任务，请先修改或删除')
            return redirect('/assignments/%d' % obj.id)
        if obj.ass_researches.count() > 0:
            flash('当前任务书下还存在与之关联的可研任务，请先修改或删除')
            return redirect('/assignments/%d' % obj.id)
        if obj.ass_tasks_develop.count() > 0:
            flash('当前任务书下还存在与之关联的非开发任务，请先修改或删除')
            return redirect('/assignments/%d' % obj.id)
        
        view = DeleteView('requirement', ok_url=get_url('list'), obj=obj)
        return view.run()
    else:
        return error("你无权删除准开发需求！")

@expose('/assignments/<int:id>')
def assignments_view(id):
    from uliweb.utils.generic import DetailView
    from uliweb.orm import get_model
    from uliweb.utils.common import get_choice
    from uliweb import orm

    def stage(value, obj):
        return get_choice(settings.PARA.ASSIGNMENT_STAGE[obj.type], value)
    
    view = DetailView('assignment', condition=int(id))
    view.fields_convert_map = {'stage':stage, 'risk_if':boolean_convert, 'advanced_if':boolean_convert}
    
    return g_views.generic_view(model, id, get_url=get_url, layout=layout, 
        title='查看任务书', view=view, template='assignments_view.html')

@expose('/assignments/query')
def assignments_query():
    from uliweb.orm import get_model
    Assignment = get_model('assignment')
    result = []
    query = Assignment.get_user_assignments(request.user, not_in=())
    for row in query:
        result.append([row.id, unicode(row)])
    return json(result)

@expose('/assignments/search')
def assignments_query():
    from uliweb.orm import get_model
    from sqlalchemy.sql import or_
    
    Assignment = get_model('assignment')
    result = []
    query = Assignment.get_user_assignments(request.user, not_in=())
    condition = None
    if 'term' in request.values:
        term = request.values['term']
        condition = or_(Assignment.c.ass_id.like('%'+term+'%'),
            Assignment.c.name.like('%'+term+'%'))
    for row in query.filter(condition):
        result.append([row.id, unicode(row)])
    return json(result)
